package com.ecp.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

public class DateUtil {

	public static final String FORMAT_LONGDATETIME = "yyyy-MM-dd HH:mm:ss.SSS";
	public static final String FORMAT_SHORTDATETIME = "yyyy-MM-dd";
	public static final String FORMAT_LONGDATETIME_COMPACT = "yyyyMMddHHmmssSSS";
	public static final String FORMAT_SHORTDATETIME_COMPACT = "yyyyMMdd";
	public static final String FORMAT_TIME = "yyyy-MM-dd HH:mm:ss";

	public static String getStringFormatByTimestamp(Timestamp argDate,
			String fFlag) {
		String strDateTime = "";
		try {
			SimpleDateFormat objSDF = new SimpleDateFormat(fFlag.trim());
			strDateTime = objSDF.format(argDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strDateTime;
	}

	public static String getStringFormatByDate(Date argDate, String fFlag) {
		String strDateTime = "";
		try {
			SimpleDateFormat objSDF = new SimpleDateFormat(fFlag.trim());
			strDateTime = objSDF.format(argDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strDateTime;
	}

	public static Date getDateFormatByString(String argDate, String fFlag) {
		if (argDate == null || argDate.equalsIgnoreCase("")) {
			return null;
		}
		Date v = null;
		try {
			SimpleDateFormat objSDF = new SimpleDateFormat(fFlag.trim());
			v = objSDF.parse(argDate);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return v;
	}

	public static java.sql.Timestamp getDateTimeFormatByString(String argDate,
			String fFlag) {
		if (argDate == null) {
			return null;
		}
		java.sql.Timestamp tt = null;
		try {
			int lng = argDate.trim().length();
			SimpleDateFormat objSDF = new SimpleDateFormat(fFlag);
			objSDF.applyPattern(fFlag.trim().substring(0, lng));
			tt = new java.sql.Timestamp(objSDF.parse(argDate).getTime());
		} catch (Exception e) {
			try {
				tt = formatDateTime(argDate, fFlag, null);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return tt;
	}

	private static Timestamp formatDateTime(String argDate, String fFlag,
			Locale locale) {
		Timestamp tt = null;
		try {
			if (locale == null) {
				locale = Locale.getDefault();
			}
			SimpleDateFormat objSDF = new SimpleDateFormat(fFlag, locale);
			@SuppressWarnings("deprecation")
			Date date = new Date(argDate);
			String s = objSDF.format(date);
			int lng = s.trim().length();
			objSDF.applyPattern(fFlag.trim().substring(0, lng));
			tt = new Timestamp(objSDF.parse(s).getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tt;

	}

	public static String getNowStringDate() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		return simpleDateFormat.format(new Date());
	}

	public static String getNowStringDateForSSS() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ssSS");
		return simpleDateFormat.format(new Date());
	}

	public static Timestamp getNowDateTime() {
		return getMasterDateTime();
	}

	public static Timestamp getMasterDateTime() {
		return new Timestamp(Calendar.getInstance().getTimeInMillis());
	}

	public static Date getBeforeAfterDate(String date, int day) {
		SimpleDateFormat df = new SimpleDateFormat(FORMAT_TIME);
		Date olddate = null;
		try {
			df.setLenient(false);
			olddate = new Date(df.parse(date).getTime());
		} catch (ParseException e) {
			throw new RuntimeException("日期转换错误");
		}
		Calendar cal = new GregorianCalendar();
		cal.setTime(olddate);

		int Year = cal.get(Calendar.YEAR);
		int Month = cal.get(Calendar.MONTH);
		int Day = cal.get(Calendar.DAY_OF_MONTH);

		int NewDay = Day + day;

		cal.set(Calendar.YEAR, Year);
		cal.set(Calendar.MONTH, Month);
		cal.set(Calendar.DAY_OF_MONTH, NewDay);

		return new java.sql.Date(cal.getTimeInMillis());
	}

	public static String getBeginDateOfMonth() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String beginDate = "";
		Calendar cal = Calendar.getInstance();
		try {
			cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
			Date beginTime = cal.getTime();
			beginDate = sdf.format(beginTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return beginDate;
	}

	public static String getEndDateOfMonth() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String endDate = "";
		Calendar cal = Calendar.getInstance();
		try {
			cal.set(Calendar.DATE, 1);
			cal.roll(Calendar.DATE, -1);
			Date endTime = cal.getTime();
			endDate = sdf.format(endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return endDate;
	}

	public static String lastWeek() {
		Date date = new Date();
		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(date));
		int day = Integer.parseInt(new SimpleDateFormat("dd").format(date)) - 6;

		if (day < 1) {
			month -= 1;
			if (month == 0) {
				year -= 1;
				month = 12;
			}
			if (month == 4 || month == 6 || month == 9 || month == 11) {
				day = 30 + day;
			} else if (month == 1 || month == 3 || month == 5 || month == 7
					|| month == 8 || month == 10 || month == 12) {
				day = 31 + day;
			} else if (month == 2) {
				if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
					day = 29 + day;
				else
					day = 28 + day;
			}
		}
		String y = year + "";
		String m = "";
		String d = "";
		if (month < 10)
			m = "0" + month;
		else
			m = month + "";
		if (day < 10)
			d = "0" + day;
		else
			d = day + "";

		return y + "-" + m + "-" + d;
	}

	// 获得一月前的日期
	public String lastMonth() {
		Date date = new Date();
		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(date)) - 1;
		int day = Integer.parseInt(new SimpleDateFormat("dd").format(date));
		if (month == 0) {
			year -= 1;
			month = 12;
		} else if (day > 28) {
			if (month == 2) {
				if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
					day = 29;
				} else
					day = 28;
			} else if ((month == 4 || month == 6 || month == 9 || month == 11)
					&& day == 31) {
				day = 30;
			}
		}
		String y = year + "";
		String m = "";
		String d = "";
		if (month < 10)
			m = "0" + month;
		else
			m = month + "";
		if (day < 10)
			d = "0" + day;
		else
			d = day + "";

		return y + "-" + m + "-" + d;
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static Date[] getToDayAndTomorrow(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date[] days = new Date[2];
		try {
			if (date == null) {
				date = new Date();
			}
			String todayStr = sdf.format(date);
			Date today = sdf.parse(todayStr);

			Calendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(Calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
			date = calendar.getTime(); // 这个时间就是日期往后推一天的结果

			String tomorrowStr = sdf.format(date);
			Date tomorrow = sdf.parse(tomorrowStr);
			days[0] = today;
			days[1] = tomorrow;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return days;
	}

	public static String[] getBeginDateAndEndDate(String dateStr) {
		String[] result = new String[2];
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(dateStr);
			Calendar calendar = Calendar.getInstance(Locale.CHINA);
			calendar.setTime(date);
			int miniDay = calendar.getMinimum(Calendar.DAY_OF_MONTH);
			calendar.set(Calendar.DAY_OF_MONTH, miniDay);
			Date beginDate = calendar.getTime();
			result[0] = sdf.format(beginDate);
			int maxDay = calendar.getMaximum(Calendar.DAY_OF_MONTH);
			calendar.set(Calendar.DAY_OF_MONTH, maxDay);
			Date endDate = calendar.getTime();
			result[1] = sdf.format(endDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取当前日期的 前后日期
	 * 
	 * @param date
	 * @param unit
	 *            1-天 ；2-月 ；3-年
	 * @param period
	 * */
	public static String getBeforeAfterDate(String srcDate, int unit, int period) {
		SimpleDateFormat df = new SimpleDateFormat(FORMAT_SHORTDATETIME);
		Date olddate = null;
		try {
			df.setLenient(false);
			olddate = new Date(df.parse(srcDate).getTime());
		} catch (ParseException e) {
			throw new RuntimeException("日期转换错误");
		}
		Calendar cal = new GregorianCalendar();
		cal.setTime(olddate);

		int timeField = -1;
		if (unit == 1) {
			timeField = Calendar.DAY_OF_YEAR;
		} else if (unit == 2) {
			timeField = Calendar.MONTH;
		} else if (unit == 3) {
			timeField = Calendar.YEAR;
		}

		cal.add(timeField, period);

		return getStringFormatByDate(cal.getTime(), FORMAT_SHORTDATETIME);
	}

	// 比较两个时间的大小
	public static boolean compare_date(String DATE1, String DATE2, String DATE3) {
		SimpleDateFormat df = new SimpleDateFormat("HH:mm");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			Date dt3 = df.parse(DATE3);
			if (dt1.getTime() >= dt2.getTime()
					&& dt1.getTime() <= dt3.getTime()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
    public static String getBetweenTime(String startDate,String endDate){
  	  SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long between = 0;
        try {
            java.util.Date begin = dfs.parse(startDate);
            java.util.Date end = dfs.parse(endDate);
            between = (end.getTime() - begin.getTime());// 得到两者的毫秒数
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        long day = between / (24 * 60 * 60 * 1000);
        long hour = (between / (60 * 60 * 1000) - day * 24);
        long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
//        long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
//        long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
        
        String str = "";
        if(day >0){
      	  str =  day + "天" + hour + "小时" + min + "分";
        }else if(day ==0){
      	  str =  hour + "小时" + min + "分";
        }
        return str;
    }
    
    public static String getDateYM(String date){
    	if(date.length() > 7){
    		return date.substring(0,4)  + "年"+ date.substring(5,7) +"月";
    	}else{
    		return "";
    	}
    }
    
    
	/**
	 * 获取当前日期的 前后小时的时间
	 * 如果超过当天时间则返回23:59:59
	 * 
	 * @param date
	 * @param period
	 * */
	public static String getBeforeAfterTime(Date srcDate, int period) {
		
		Calendar cal = new GregorianCalendar();
		cal.setTime(srcDate);

		int timeField = Calendar.HOUR_OF_DAY;

		cal.add(timeField, period);
		
		Date destDate = cal.getTime();
		String srcD = getStringFormatByDate(srcDate, FORMAT_SHORTDATETIME);
		String destD = getStringFormatByDate(destDate, FORMAT_SHORTDATETIME);
		String destTime = "";
		if(destD.equals(srcD)){
			destTime = getStringFormatByDate(destDate, FORMAT_TIME);
			if(destTime.length() > 18 ){
				destTime = destTime.substring(11,16);
			}else{
				destTime = "00:00";
			}
		}else{
			destTime = "23:59";
		}
		
		return destTime;
	}
	
	/**
	 * 判断传入日期是否当天
	 * 
	 * @param d
	 * */
	public static String getTime(Date d){

		DateFormat d4 = DateFormat.getTimeInstance(); 
	     String str4 = d4.format(d);
	     return str4;
	}
	
	
	
	/**
	 * 判断传入日期是否当天
	 * 
	 * @param cDate  yyyy-MM-dd
	 * */
	public static boolean  isCurrentDay(String cDate){
		String destD = getStringFormatByDate(new Date() , FORMAT_SHORTDATETIME);
		return cDate.equals(destD) ;
	}
	
	/**
	 * 判断传入日期是否周末
	 * 
	 * @param cDate 
	 * */
	public static boolean  isWeekend(Date cDate){
		 Calendar cal = Calendar.getInstance();
		 cal.setTime(cDate);
		 boolean ret = false;
		 if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
		    	ret =true;
		 }
		return ret;
	}
	
	public static String  getNewTime(String time, int num){
		String[] t = time.split(":");
		int h = Integer.valueOf(t[0]);
		int m =  Integer.valueOf(t[1]);
		
		int newM = m - num;
		if(newM < 0 ){
			return (h - 1) +":"+(60 + newM);
		}else{
			return h +":"+newM;
		}
	}
	
	public static void main(String[] args) throws ParseException {
		
//		System.out.println( getBeforeAfterTime(new Date(), 2) ); 
		
		System.out.println(getNewTime("23:45",30)); 
		
		
		 String s1 = "12:45";
		 String s2 = "00:01";
		 String s3 = "10:2";

		 System.out.println(compare_date(s1, s2, s3));

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// String dstr = "2015-11-11";
		// Date date = sdf.parse(dstr);
		// int i = daysBetween(new Date(), date);
		// System.out.println(i);

		// String d = getBeforeAfterDate("2012-10-12",1,-1);
		// System.out.println(d);
	}

}
